package com.atguigu.gmall.product.utils;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传工具类
 */
public class FileUploadUtils {
    private static TrackerClient trackerClient = null;
    static {
        try {
            String path = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
            //0.设置配置文件的位置进行读取   init IO流 读取配置文件 必须是绝对路径
            ClientGlobal.init(path);
            //1.连接Tracker跟踪器
            trackerClient = new TrackerClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //文件上传
    public static String uploadFile(byte[] file, String ext){
        try {
            //2.返回存储节点的地址
            TrackerServer trackerServer = trackerClient.getConnection();
            //3.连接存储节点
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
            //4.上传文件
            String fileId = storageClient1.upload_file1(file, ext, null);
            System.out.println(fileId);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
